package cn.luoshaocheng.user.controller;

import cn.luoshaocheng.basic.exception.BusinessException;
import cn.luoshaocheng.basic.util.PageList;
import cn.luoshaocheng.basic.util.jsonResult;


import cn.luoshaocheng.user.domain.User;
import cn.luoshaocheng.user.dto.RegisterDto;
import cn.luoshaocheng.user.query.UserQuery;
import cn.luoshaocheng.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController //controller层  返回的是json格式数据
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;


    /**
     * 查询全部
     *
     * @return
     */
    @GetMapping
    public List<User> loadAll() {
        return userService.loadAll();
    }

    /**
     * 查询一个
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public User loadById(@PathVariable("id") Long id) {
        return userService.loadById(id);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public jsonResult deleteById(@PathVariable("id") Long id) {
        try {
            userService.delete(id);
            return new jsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonResult.me().setMsg("删除失败");
        }
    }

    /**
     * @param
     * @return
     */
    @PutMapping
    public jsonResult addAndUpdate(@RequestBody User user) {
        try {
            if (user.getId()== null) {
                userService.save(user);
            } else {
                userService.update(user);
            }
            return new jsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonResult.me().setMsg("操作失败");
        }
    }

    /**
     * 分页数据
     *
     * @param
     * @return
     */
    @PostMapping
    public PageList<User> queryPage(@RequestBody UserQuery userQuery) {
        return userService.queryPage(userQuery);

    }

    /**
     * 批量删除
     * @param
     * @return
     */
    @PatchMapping
    public jsonResult patchDel(@RequestBody List<Long> ids) {
        try {
            userService.patchDel(ids);
            return new jsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return jsonResult.me().setMsg("删除失败");
        }
    }
    @PostMapping("/phoneRegister")
    public jsonResult phoneRegister(@RequestBody RegisterDto dto){
        try {
            userService.phoneRegister(dto);
            return jsonResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return jsonResult.me().setMsg(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return jsonResult.me().setMsg("网络异常");
        }
    }
}

